<?php

require_once('config.php');
require_once('autoloader.php');

if (isset($_GET['__FRmodule'])) {
    $module = $_GET['__FRmodule'];

    if (isset($_GET['__FRclass'])) {
            $class = $_GET['__FRclass'];
        } else {
            $class = $module;
        }
    
    if ($module == "rest") {
        
        $method = $_SERVER['REQUEST_METHOD'];
        
       if ($method == "POST"){
           $action = 'POST';
       }else if ($method == "GET"){
           $action = 'GET';
       }else if ($method == "PUT"){
           $action = 'PUT';
       }else if ($method == "DELETE"){
           $action = 'DELETE';
       }else{
              die("Wrong method/action");
       }
        
    } else {
        if (isset($_GET['__FRaction']) && trim($_GET['__FRaction']) != "") {
            $action = $_GET['__FRaction'];
        } else {
           die("Wrong action");
        }

    }


    $classFile = FR_APPLICATION_DIR . '/' . $module . '/' . $class . '.php';

    if (file_exists($classFile)) {
        require_once($classFile);
        if (class_exists($class)) {
            try {
                $instance = new $class();
                if (!FR_Module::isValid($instance)) {
                    die("FEJL! Det ønskede modul er ikke validt!");
                }
                $instance->moduleName = $module;

                try {
                    if ($module == "rest"){
                        if ($method == "GET"){
                            $post_vars = array();
                            if (is_array($_GET)){
                                foreach (array_keys($_GET) as $key){
                                    if (substr($key, 0, 4) != "__FR"){
                                        $post_vars[$key] = $_GET[$key];
                                    }
                                }
                            }
                        }else{
                            parse_str(file_get_contents("php://input"),$post_vars);
                        }
                        $result = $instance->$action($post_vars);
                    }else{
                        $result = $instance->$action();
                    }
                    $presenter = FR_Presenter::factory($instance);
                    $presenter->display();
                } catch (Exception $error) {
                    die($error->getMessage());
                }
            } catch (Exception $error) {
                die($error->getMessage());
            }
        } else {
            die("FEJL! Kunne ikke finde et validt modul!");
        }
    } else {
        echo FR_APPLICATION_DIR;
        echo "<hr>";
        die("Kunne ikke finde: $classFile");
    }
} else {
    die("Følgende modul er ikke validt: $module");
}

